package com.itcoon.cloud.framework.mybatis.typehandler;

import com.itcoon.cloud.framework.enums.ValueEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public abstract class AbstractValueEnumToStringTypeHandler<V extends Serializable, E extends Enum<E> & ValueEnum<V, E>> extends BaseTypeHandler<E> {

    private final Class<E> type;

    public AbstractValueEnumToStringTypeHandler(Class<E> type) {
        if(type == null){
            throw new IllegalArgumentException("Enum class can not be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, E e, JdbcType jdbcType) throws SQLException {
        Serializable value = e.value();
        preparedStatement.setObject(i, value);
    }

    @Override
    public E getNullableResult(ResultSet resultSet, String columnLabel) throws SQLException {
        V value = (V)resultSet.getObject(columnLabel);
        return ValueEnum.fromValue(value, type);
    }

    @Override
    public E getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        V value = (V)resultSet.getObject(columnIndex);
        return ValueEnum.fromValue(value, type);
    }

    @Override
    public E getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        V value = (V)callableStatement.getObject(columnIndex);
        return ValueEnum.fromValue(value, type);
    }


}
